package com.rabbiter.oes.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbiter.oes.entity.FillQuestion;
import com.rabbiter.oes.entity.PaperManage;
import com.rabbiter.oes.mapper.FillQuestionMapper;
import com.rabbiter.oes.mapper.PaperMapper;
import com.rabbiter.oes.service.FillQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FillQuestionServiceImpl extends ServiceImpl<FillQuestionMapper, FillQuestion> implements FillQuestionService {

    // 试卷与题目对应关系
    @Autowired
    private PaperMapper paperMapper;

    /**
     * 根据试卷编号获取填空题信息
     * @param paperId 试卷编号
     * @return
     */
    @Override
    public List<FillQuestion> findByIdAndType(Integer paperId) {

        LambdaQueryWrapper<PaperManage> paperWrapper = Wrappers.lambdaQuery(PaperManage.class).
                eq(PaperManage::getQuestionType, 2).eq(PaperManage::getPaperId, paperId);
        List<PaperManage> paperManages = paperMapper.selectList(paperWrapper);
        if (CollectionUtil.isNotEmpty(paperManages)) {
            // 筛出题目id
            List<Integer> questionIds = paperManages.stream().map(PaperManage::getQuestionId).collect(Collectors.toList());
            // 查出题目信息
            return baseMapper.selectBatchIds(questionIds);
        }

        return new ArrayList<FillQuestion>();
    }

    @Override
    public IPage<FillQuestion> findAll(Page<FillQuestion> page) {
        return baseMapper.findAll(page);
    }

    @Override
    public FillQuestion findOnlyQuestionId() {
        LambdaQueryWrapper<FillQuestion> wrapper = Wrappers.lambdaQuery(FillQuestion.class);
        wrapper.orderByDesc(FillQuestion::getQuestionId);

        List<FillQuestion> fillQuestions = baseMapper.selectList(wrapper);

        if (CollectionUtil.isNotEmpty(fillQuestions)) {
            return fillQuestions.get(0);
        }else {
            FillQuestion fillQuestion = new FillQuestion();
            fillQuestion.setQuestionId(1);
            return fillQuestion;
        }
    }

    @Override
    public Integer add(FillQuestion fillQuestion) {
        baseMapper.insert(fillQuestion);
        return fillQuestion.getQuestionId();
    }

    @Override
    public List<Integer> findBySubject(Integer pageNo) {
        return baseMapper.findBySubject(pageNo);
    }

    @Override
    public int edit(FillQuestion fillQuestion) {
        return baseMapper.updateById(fillQuestion);
    }
}
